//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package test;

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class OnlineActivity {
    private JFrame activityFrame;
    private DefaultTableModel activityModel;
    private JTable activityTable;

    public OnlineActivity() {
        this.initializeDatabase();
        this.activityFrame = new JFrame("线上活动");
        this.activityFrame.setSize(800, 600);
        this.activityFrame.setLocationRelativeTo((Component)null);
        String[] columns = new String[]{"活动名称", "活动时间", "报名人数", "状态"};
        this.activityModel = new DefaultTableModel(columns, 0) {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        this.activityTable = new JTable(this.activityModel);
        this.loadActivitiesFromDatabase();
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton joinBtn = new JButton("报名参加");
        JButton addBtn = new JButton("发布活动");
        JButton backBtn = new JButton("返回主菜单");
        Font btnFont = new Font("SimSun", 0, 14);
        joinBtn.setFont(btnFont);
        addBtn.setFont(btnFont);
        backBtn.setFont(btnFont);
        joinBtn.addActionListener((e) -> this.joinActivity());
        addBtn.addActionListener((e) -> this.showAddActivityDialog());
        backBtn.addActionListener((e) -> {
            this.activityFrame.dispose();
            (new Menu(null)).setVisible(true);
        });
        buttonPanel.add(joinBtn);
        buttonPanel.add(addBtn);
        buttonPanel.add(backBtn);
        this.activityFrame.add(new JScrollPane(this.activityTable), "Center");
        this.activityFrame.add(buttonPanel, "South");
    }

    private void initializeDatabase() {
        String sql = "CREATE TABLE IF NOT EXISTS online_activities (id INT AUTO_INCREMENT PRIMARY KEY,activity_name VARCHAR(255) NOT NULL,activity_time VARCHAR(100) NOT NULL,participants INT DEFAULT 0,status VARCHAR(20) DEFAULT '报名中',description TEXT)";

        try (
                Connection conn = this.getConnection();
                Statement stmt = conn.createStatement();
        ) {
            stmt.execute(sql);
        } catch (SQLException e) {
            this.showErrorDialog("数据库初始化失败", e);
        }

    }

    private void loadActivitiesFromDatabase() {
        String sql = "SELECT activity_name, activity_time, participants, status FROM online_activities ORDER BY id DESC";

        try (
                Connection conn = this.getConnection();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
        ) {
            while(rs.next()) {
                this.activityModel.addRow(new Object[]{rs.getString("activity_name"), rs.getString("activity_time"), rs.getInt("participants"), rs.getString("status")});
            }
        } catch (SQLException e) {
            this.showErrorDialog("加载活动失败", e);
        }

    }

    private void joinActivity() {
        int selectedRow = this.activityTable.getSelectedRow();
        if (selectedRow >= 0) {
            String activityName = (String)this.activityModel.getValueAt(selectedRow, 0);
            int confirm = JOptionPane.showConfirmDialog(this.activityFrame, "确定要报名参加" + activityName + "吗?", "确认报名", 0);
            if (confirm == 0) {
                if (this.updateParticipantCount(activityName)) {
                    this.refreshActivityList();
                    JOptionPane.showMessageDialog(this.activityFrame, "报名成功!");
                } else {
                    JOptionPane.showMessageDialog(this.activityFrame, "报名失败!", "错误", 0);
                }
            }
        }

    }

    private boolean updateParticipantCount(String activityName) {
        String sql = "UPDATE online_activities SET participants = participants + 1 WHERE activity_name = ?";

        try {
            boolean var5;
            try (
                    Connection conn = this.getConnection();
                    PreparedStatement pstmt = conn.prepareStatement(sql);
            ) {
                pstmt.setString(1, activityName);
                var5 = pstmt.executeUpdate() > 0;
            }

            return var5;
        } catch (SQLException e) {
            this.showErrorDialog("更新报名人数失败", e);
            return false;
        }
    }

    private void showAddActivityDialog() {
        JDialog dialog = new JDialog(this.activityFrame, "发布新活动", true);
        dialog.setSize(500, 300);
        dialog.setLocationRelativeTo(this.activityFrame);
        JPanel panel = new JPanel(new GridLayout(4, 2));
        panel.add(new JLabel("活动名称:"));
        JTextField nameField = new JTextField();
        panel.add(nameField);
        panel.add(new JLabel("活动时间:"));
        JTextField timeField = new JTextField();
        panel.add(timeField);
        panel.add(new JLabel("活动描述:"));
        JTextArea descField = new JTextArea(3, 20);
        panel.add(new JScrollPane(descField));
        JButton submitBtn = new JButton("发布");
        submitBtn.setFont(new Font("SimSun", 0, 14));
        submitBtn.addActionListener((ev) -> {
            if (!nameField.getText().isEmpty() && !timeField.getText().isEmpty()) {
                if (this.addActivityToDatabase(nameField.getText(), timeField.getText(), descField.getText())) {
                    this.refreshActivityList();
                    dialog.dispose();
                } else {
                    JOptionPane.showMessageDialog(dialog, "发布活动失败!", "错误", 0);
                }
            }

        });
        panel.add(submitBtn);
        dialog.add(panel);
        dialog.setVisible(true);
    }

    private boolean addActivityToDatabase(String name, String time, String description) {
        String sql = "INSERT INTO online_activities (activity_name, activity_time, description) VALUES (?, ?, ?)";

        try {
            boolean var7;
            try (
                    Connection conn = this.getConnection();
                    PreparedStatement pstmt = conn.prepareStatement(sql);
            ) {
                pstmt.setString(1, name);
                pstmt.setString(2, time);
                pstmt.setString(3, description);
                var7 = pstmt.executeUpdate() > 0;
            }

            return var7;
        } catch (SQLException e) {
            this.showErrorDialog("添加活动失败", e);
            return false;
        }
    }

    private void refreshActivityList() {
        this.activityModel.setRowCount(0);
        this.loadActivitiesFromDatabase();
    }

    private Connection getConnection() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/community_db?" +
                "useSSL=false&" +
                "serverTimezone=UTC&" +
                "allowPublicKeyRetrieval=true";
        String user = "root";
        String password = "Ht20041228";
        return DriverManager.getConnection(url, user, password);
    }

    private void showErrorDialog(String title, Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(this.activityFrame, title + ": " + e.getMessage(), "错误", 0);
    }

    public void show() {
        this.activityFrame.setVisible(true);
    }
}
